package game.ai.fsm;
import game.objects.npc.FSMNPC;

import java.util.Vector;

import tools.Floatmath;
import tools.Help;
public class State {
	public String name;
	public Vector<Transition> transitions;
	public Vector<Condition> conditions;
	private StateHandler statehandler;
	private long mintime;
	private long switchtime;
	private Transition timeouttransition;
	public State(FSMNPC npc, String name, long mintime, StateHandler statehandler) {
		this.name = name;
		transitions = new Vector<Transition>();
		conditions = new Vector<Condition>();
		this.mintime = mintime;
		if (statehandler != null) {
			this.statehandler = statehandler;
		}
		else {
			this.statehandler = new VoidStateHandler();
		}
		npc.addState(this);
	}
	public State(FSMNPC npc, String name, long mintime) {
		this(npc, name, mintime, null);
	}
	public State(FSMNPC npc, String name, StateHandler sthandler) {
		this(npc, name, -1, sthandler);
	}
	public State(FSMNPC npc, String name) {
		this(npc, name, -1, null);
	}
	public void handle() {
		if (statehandler != null)
			statehandler.handle();
		else
			Help.p("ERROR no state handler!!!");
	}
	public void addTransition(Transition t) {
		transitions.add(t);
		conditions.add(t.condition);
	}
	public void remTransition(Transition t) {
		conditions.remove(t.condition);
		transitions.remove(t);
	}
	public State switchTo() {
		// Help.p("->"+this.name);
		this.switchtime = System.currentTimeMillis();
		return this;
	}
	public State getNext() {
		if (switchtime != -1 && System.currentTimeMillis() - switchtime < mintime) {
			// Help.p(name+" t:"+(System.currentTimeMillis()-switchtime));
			return this;
		}
		else {
			if (switchtime != -1 && System.currentTimeMillis() - switchtime > mintime && this.timeouttransition != null) {
				// Help.p(timeouttransition.condition.name+" reached");
				return timeouttransition.nextState.switchTo();
			}
			for (Transition t : transitions) {
				if (t.condition.fulfilled) {
					// Help.p(t.condition.name+" = true");
					return t.nextState.switchTo();
				}
			}
			return this;
		}
	}
	public Vector<Condition> getConditions() {
		return conditions;
	}
	public void setTimeOutTransition(Transition transition) {
		this.timeouttransition = transition;
	}
}
